import * as types from './mutation-types'

const mutations = {
  [types.ADD_SHOPCATE] (state, goodsinfo) {
    var flag = false
    state.shoplist.forEach(element => {
      if (element.id === goodsinfo.id) {
        element.count = goodsinfo.count + element.count
        flag = true
      }
    })
    if (!flag) {
      state.shoplist.push(goodsinfo)
    }

    localStorage.setItem('shoplist', JSON.stringify(state.shoplist))
  },
  [types.UPDATE_SHOPCATE] (state, goodsinfo) {
    state.shoplist.forEach(element => {
      if (element.id === goodsinfo.id) {
        element.count += goodsinfo.count
      }
      if (element.count < 0) {
        element.count = 0
      }
    })

    localStorage.setItem('shoplist', JSON.stringify(state.shoplist))
  },
  [types.ADD_COUNT] (state, n) {
    state.count += 1
  },
  [types.DELETE_GOODS] (state, id) {
    state.shoplist.some((item, i) => {
      if (item.id === id) {
        state.shoplist.splice(i, 1)
        return true
      }
    })
    localStorage.setItem('shoplist', JSON.stringify(state.shoplist))
  },
  [types.CHANGE_SELECT] (state, changeinfo) {
    state.shoplist.some(item => {
      if (item.id === changeinfo.id) {
        item.selected = changeinfo.selected
        return true
      }
    })
    localStorage.setItem('shoplist', JSON.stringify(state.shoplist))
  }
}

export default mutations
